#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: KevinQi
@file: main.py
@time: 2023/12/26 1:58
@desc: base on tornado web system for admin!
"""
import sys
import os

# 把当前文件所在文件夹的父文件夹路径加入到PYTHONPATH
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import traceback
import tornado
from tornado import ioloop
from conf import config
from backend.workjob.urls.urls_utils import urls
from backend.workjob.utils import create_tables
from backend.workjob.utils.log_utls import app_log


class Application(tornado.web.Application):
    def __init__(self):
        try:
            handlers = urls
            tornado.web.Application.__init__(self, handlers=handlers, **config.settings)
        except Exception:
            app_log.error("oooo....something wrong, restart ...")
            app_log.error(traceback.format_exc())
            ioloop.IOLoop.current().stop()


if __name__ == "__main__":
    try:
        if config.create_tables:
            create_tables.run()
        app_log.info("create server start")
        http_server = tornado.httpserver.HTTPServer(Application())
        http_server.listen(port=config.settings.get("port"), address=config.settings.get("host"))
        app_log.info(f"Listening on TCP address http://{config.settings.get('host')}:{config.settings.get('port')}")
        app_log.info("start server successful")
        tornado.ioloop.IOLoop.instance().start()
    except Exception as e:
        print('start error')
        app_log.error("ooops,something wrong, restart ...")
        app_log.error(traceback.format_exc())
        print(traceback.format_exc())
        ioloop.IOLoop.current().stop()
